package io.xccit.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.deploy.net.URLEncoder;
import io.xccit.pojo.User;
import io.xccit.pojo.dto.UserDTO;
import io.xccit.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin //解决跨域
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService service;

    /**
     * 登录接口
     * @param userDTO
     * @return
     */
    @PostMapping("/login")
    public UserDTO login(@RequestBody UserDTO userDTO){
        return service.login(userDTO);
    }
    /**
     * 查询所有接口
     * @return
     */
    @GetMapping("/findAll")
    public List<User> findAll(){
        return service.list();
//        return service.findAll();
    }

    /**
     * 添加用户(注册)接口
     * @param user
     * @return
     */
    @PostMapping("/add")
    public boolean insert(@RequestBody User user){
        return service.save(user);
    }

    /**
     * 更新用户接口
     * @param user
     * @return
     */
    @PostMapping("/update")
    public Integer update(@RequestBody User user){
        return service.update(user);
    }

    /**
     * 删除用户接口
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Integer delete(@PathVariable Integer id){
        return service.delete(id);
    }

    /**
     *
     * @param ids
     * @return
     */
    @PostMapping("/delete/batch")
    public boolean batchDelete(@RequestBody List<Integer> ids){
        return service.batchDelete(ids);
    }

    /**
     * 分页查询接口 mybatis
     * @param pageNum
     * @param pageSize
     * @return
     */
/*    @GetMapping("/page")
    public Map<String,Object> pageFind(@RequestParam("pageNum") Integer pageNum,@RequestParam("pageSize") Integer pageSize){
        Map<String,Object> map = new HashMap<>();
        pageNum = (pageNum - 1) * pageSize;
        Integer total = service.total();
        List<User> users = service.pageFind(pageNum,pageSize);
        map.put("users",users);
        map.put("total",total);
        return map;
    }  */

    /**
     * mybatisplus 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public IPage<User> pageFind(@RequestParam("pageNum") Integer pageNum,
                                @RequestParam("pageSize") Integer pageSize,
                                @RequestParam("descVal") boolean desc){
        IPage<User> page = new Page<>(pageNum,pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(desc){
            queryWrapper.orderByDesc("id");
        }else{
            queryWrapper.orderByAsc("id");
        }
        return service.page(page,queryWrapper);
    }

    /**
     * 根据用户名模糊查询
     * @param username
     * @return
     */
    @GetMapping("findbyusername")
    public IPage<User> findByUserName(@RequestParam("pageNum") Integer pageNum,
                                      @RequestParam("pageSize") Integer pageSize,
                                      @RequestParam("username") String username){
        IPage<User> page = new Page<>(pageNum,pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("username",username);
        return service.page(page,queryWrapper);
    }

    /**
     * 用户导出
     * @param response
     * @throws IOException
     */
    @GetMapping("/export")
    public void exportUser(HttpServletResponse response) throws IOException {
        List<User> users = service.list();
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("username","账号");
        writer.addHeaderAlias("password","密码");
        writer.addHeaderAlias("nickname","昵称");
        writer.addHeaderAlias("email","邮箱");
        writer.addHeaderAlias("phone","电话");
        writer.addHeaderAlias("address","地址");
        writer.addHeaderAlias("createTime","创建时间");
        writer.addHeaderAlias("avatar","头像");
        writer.write(users,true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream stream = response.getOutputStream();
        writer.flush(stream,true);
        stream.close();
        writer.close();
    }

    /**
     * 用户导入接口
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/import")
    public boolean importUser(MultipartFile file) throws IOException {
        InputStream fileInputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(fileInputStream);
        /**
         * 要求表头必须是英文且与JavaBean保持一致
         */
        List<User> users = reader.readAll(User.class);
        fileInputStream.close();
        return service.saveBatch(users);
    }
}
